use gloo::console;
use thiserror::Error;
use web_sys::window;
use yew::html::RenderError;
use yew::suspense::Suspension;

#[derive(Error, Debug)]
pub enum AppError {
    #[error("未知错误")]
    Unknown,
    #[error("RequestError:{0}")]
    RequestError(#[from] reqwest::Error),
    #[error("Serde Json error:{0}")]
    SerdeJsonError(#[from] serde_json::Error),
    #[error("url parse error:{0}")]
    UrlParseError(#[from] url::ParseError),
}

impl From<AppError> for RenderError {
    fn from(val: AppError) -> Self {
        console::error!(format!("!!错误!!:{}", val));
        RenderError::Suspended(Suspension::new().0)
    }
}

impl AppError {
    pub fn report(&self, title: &str) {
        let msg = &format!("{} err:{}", title, self);
        console::log!(msg);
        let window = window().expect("获取window失败");
        window.alert_with_message(msg).expect("alert 启动失败");
    }
}
